package com.wswy.wzcx.ui.user

import android.app.Dialog
import android.arch.lifecycle.Observer
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.animation.AnimationUtils
import com.che.libcommon.utils.ToastUtils
import com.chuanglan.shanyan_sdk.OneKeyLoginManager
import com.wswy.wzcx.R
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.BizReport
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.utils.NetUtils
import kotlinx.android.synthetic.main.fragment_login_frontend.*
import org.json.JSONObject
import timber.log.Timber


/**
 * 登录注册 统一打开页面
 */
class LoginFrontendFragment : BaseVerifyFragment() {

    companion object {
        private const val TAG = "LoginFrontendFragment"
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_login_frontend
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        initViews()

    }


    private val handler = Handler()
    private var dialog: Dialog? = null

    override fun lockLoad() {
        super.lockLoad()

        ll_login_phone.isClickable = false
        ll_login_wechat.isClickable = false

        ll_btn_login.isClickable = false
    }

    override fun unlockLoad() {
        super.unlockLoad()
        ll_login_phone.isClickable = true
        ll_login_wechat.isClickable = true

        ll_btn_login.isClickable = true
    }

    private fun initViews() {
        ll_btn_login.normal(getString(R.string.one_key_login))
        ll_btn_login.isEnabled = true
//        tv_service_agreement.text = SpannableStringBuilder().run {
//            append(getString(R.string.login_service_agreement))
//
//            append(SpannableString(getString(R.string.login_user_service_agreement)).apply {
//
//                setSpan(ForegroundColorSpan(ContextCompat.getColor(AppContext.getContext(),R.color.colorPrimary)),
//                        0,this.length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//
//                setSpan(object :ClickableSpan(){
//
//                    override fun updateDrawState(ds: TextPaint) {
//                        super.updateDrawState(ds)
//                        ds.isUnderlineText = false
//                    }
//
//                    override fun onClick(widget: View) {
//
//                        WebViewActivity.startWebview(widget.context, "file:///android_asset/html/user_agree.html")
//
//                    }
//
//                },0,this.length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//
//            })
//
//        }
//
//        tv_service_agreement.movementMethod = LinkMovementMethod.getInstance()

        tv_service_protocol.highlightColor = Color.TRANSPARENT
        tv_service_protocol.movementMethod = LinkMovementMethod.getInstance()
        tv_service_protocol.text = LoginHelper.getServiceString(requireContext())

        ll_service_layout.onClick {
            img_agree_protocol.isSelected = !img_agree_protocol.isSelected
        }
        img_agree_protocol.isSelected = true

        //登录
        ll_login_phone.onClick {
            if (!checkProtocol()) {
                return@onClick
            }
            sendClickEvent(StatisticsId.u_dl)
            loginHolderViewModel.stepState.resetValue()
            loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_LOGIN)
        }
//
//        //注册
//        btn_reg.setOnClickListener {
//
//            sendClickEvent(StatisticsId.u_zc)
//
//            loginHolderViewModel.stepState.resetValue()
//
//            loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_REG)
//
//        }

        //微信登录
        ll_login_wechat.onClick {
            if (!checkProtocol()) {
                return@onClick
            }
            sendClickEvent(StatisticsId.u_wechat)
            loginHolderViewModel.stepState.resetValue()
            loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_WECHAT_LOGIN)

        }

        loginHolderViewModel.getUserLoginLiveData().observe(this, Observer {
            it?.runCatching {
                if (inLoading()) {
                    ll_btn_login.loading("登录中...")
                    lockLoad()
                } else {
                    if (isOk() && data != null) {
                        ll_btn_login.success("登录成功") {
                            handler.postDelayed({
                                loginHolderViewModel.setUserLogined(data)
                            }, 500)
                        }
                    } else {
                        ll_btn_login.fail("登录失败") {
                            unlockLoad()
                            handler.removeCallbacksAndMessages(null)
                            handler.postDelayed({
                                context?.let {
                                    ll_btn_login.normal(getString(R.string.one_key_login))
                                }
                            }, 2000)

                        }
                    }
                }

            }

        })

        ll_btn_login.onClick {
            if (!checkProtocol()) {
                return@onClick
            }
            if (!NetUtils.isNetworkAvailable(activity)) {
                ToastUtils.showText("请检查当前网络连接是否正常")
                return@onClick
            }
            loginHolderViewModel.stepState.resetValue()
            loginHolderViewModel.clickEvent(LoginHolderViewModel.CLICK_ONE_KEY_LOGIN)
            dialog = LoadingDialog(it.context, "请稍后").also {
                it.show()
            }
            OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getDialogUiConfig(requireContext()))
            OneKeyLoginManager.getInstance().openLoginAuth(true, { code, result ->
                dialog?.dismiss()
                Timber.e("---getOpenLoginAuthStatus $code   $result")
                if (code != 1000) {
                    var innerCode = JSONObject(result).optString("innerCode")
                    if (innerCode.isNotEmpty()) {
                        if (innerCode.equals("1023") ||
                                innerCode.equals("200027")
                                || innerCode.equals("80000")
                                || innerCode.equals("200023")) {
                            ToastUtils.showText("您的网络环境较差，请检查当前网络连接或稍后重试")
                        } else if (innerCode.equals("102001")) {
                            ToastUtils.showText("请切换至流量网络数据后登录，或其他方式登录")
                        } else if (innerCode.equals("200002"))
                            ToastUtils.showText("请检查是否正确插入sim卡")
                        else {
                            //ToastUtils.showText(result)
                            ToastUtils.showText("登录失败，请使用其他方式登录")
                            BizReport.sendException(BizReport.SY_ONEKEY_OPEN_ERROR, "$code:$result")
                        }
                    }
                }

            }, { code, result ->
                dialog?.dismiss()
                Timber.e("---getOneKeyLoginStatus $code   $result")
                if (code != 1000) {
                    BizReport.sendException(BizReport.SY_ONEKEY_LOGIN_ERROR, "$code:$result")
                }
                if (code == 1000 && result.isNotEmpty()) {
                    val token = kotlin.runCatching {
                        JSONObject(result).optString("token")
                    }
                    if (!TextUtils.isEmpty(token.getOrNull())) {
                        loginHolderViewModel.doLogin(token.getOrNull())
                    } else {
                        ToastUtils.showText("登录失败，请使用其他方式登录")
                    }


                }

            })
        }

    }

    private fun checkProtocol(): Boolean {
        if (!img_agree_protocol.isSelected) {
            val shake = AnimationUtils.loadAnimation(context, R.anim.anim_input)
            ll_service_layout.startAnimation(shake)
            ToastUtils.showText("请勾选同意《用户协议》及《隐私政策》")
            return false
        }
        return true
    }


    override fun onDetach() {
        super.onDetach()
        handler.removeCallbacksAndMessages(null)
    }

}